#!/bin/bash

############ script usage
function usage {
	echo -e "\n*****************************************"
	echo "* usage:"
	echo "* clean image and container   : $0 clean"
	echo "* build image                 : $0 build"
	echo "* cluster mode run            : $0 start {id}"
	echo "* standalone mode run         : $0 start"
	echo -e "*******************************************\n"
}

############ simple policy to check zoo.cfg is cluster mode or not
# return 1=cluster, 2=standalone, 3=unkown
mode_cluster=1
mode_standalone=2
mode_unknown=3
function checkIsCluster {
	serverCnt=`grep -e '^server.[1234567890]*=' ./zoo.cfg | wc -l`
	if [ $serverCnt -eq 0 ];then
		echo $mode_standalone
	elif [ $serverCnt -ge 3 ]; then
		echo $mode_cluster
	else
		echo $mode_unknown
	fi
}

############ args check
if [ $# -eq 0 ];then
	usage
	exit 1;
fi

############
action=$1
echo "action  : $action"

if [ "$action" == "start" ]; then

	mode=`checkIsCluster`

	if [ $mode -eq $mode_cluster ];then
		############cluster_mode##############
		echo "mode    : cluster"
		if [ $# -lt 2 ]; then
			echo "usage   : $0 start {id}"
			exit 1
		fi
		mkdir -p /tmp/zookeeper
		sid=$2;
		echo "serverid=$sid"
		docker run -d --net=host -v /tmp/zookeeper:/tmp/zookeeper --name zk_v1 zk_v1 $sid
		# docker run -ti --net=host -v /tmp/zookeeper:/tmp/zookeeper --name zk_v1 zk_v1 $sid

	elif [ $mode -eq $mode_standalone ];then
		############mode_standalone##############
		echo "mode    : standalone"
		mkdir -p /tmp/zookeeper
		docker run -d --net=host -v /tmp/zookeeper:/tmp/zookeeper --name zk_v1 zk_v1
		# docker run -ti --net=host -v /tmp/zookeeper:/tmp/zookeeper --name zk_v1 zk_v1

	else
		echo "mode_unknown"
		usage
		exit 1
	fi

	# mkdir -p /tmp/zookeeper
	# sid=$2;
	# echo "serverid=$sid"
	# docker run -d --net=host -v /tmp/zookeeper:/tmp/zookeeper --name zk_v1 zk_v1 $sid
elif [ "$action" == "clean" ]; then
	docker rm -f zk_v1
	docker rmi -f zk_v1
elif [ "$action" == "build" ]; then
	docker build -t zk_v1 .
else
	usage
	exit 1
fi


####### faq
# why --net=host, not use [ expose and -p 2181:2181 ]
# answer, tested, not work, machine only listen ipv6, and other cannot connect to each other with port 2888/3888